<template>
  <div class="home-dashboard">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span class="chart-title">活动分类占比</span>
            <el-date-picker
              v-model="classifyDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleClassifyDateChange"
              class="date-picker"
            >
            </el-date-picker>
          </div>
          <div class="chart-container">
            <div v-if="!classifyDateRange" class="empty-state">
              <i class="el-icon-date"></i>
              <p>请选择时间段</p>
            </div>
            <div v-else-if="!hasClassifyData" class="empty-state">
              <i class="el-icon-document"></i>
              <p>该时间段暂无数据</p>
            </div>
            <div v-else style="height: 100%; width: 100%;">
              <v-chart :options="classifyPieOptions" autoresize />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span class="chart-title">活动状态统计</span>
          </div>
          <div class="status-grid">
            <div class="status-item" v-for="(item, index) in statusData" :key="index">
              <div class="status-value">{{ item.value }}</div>
              <div class="status-label">{{ item.label }}</div>
              <div class="status-icon" :class="item.icon"></div>
              <div class="status-bg" :style="{ backgroundColor: item.color }"></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <el-card class="chart-card large">
          <div slot="header" class="card-header">
            <span class="chart-title">活动参与人数 Top10</span>
            <el-date-picker
              v-model="participantsDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleParticipantsDateChange"
              class="date-picker"
            >
            </el-date-picker>
          </div>
          <div class="chart-container large">
            <div v-if="!participantsDateRange" class="empty-state">
              <i class="el-icon-date"></i>
              <p>请选择时间段</p>
            </div>
            <div v-else-if="!hasParticipantsData" class="empty-state">
              <i class="el-icon-document"></i>
              <p>该时间段暂无数据</p>
            </div>
            <div v-else style="height: 100%; width: 100%;">
              <v-chart :options="participantsBarOptions" autoresize />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Vue from 'vue'
import VChart from 'vue-echarts'
import { getClassifyStatistics, getActivityTop10, getActivityStatistics } from '@/api/statistics'

// 手动引入 ECharts 核心模块和需要使用的图表/组件
import * as echarts from 'echarts/core'
import { PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
])

// 注册 vue-echarts 组件
Vue.component('v-chart', VChart)

export default {
  name: 'HomeDashboard',
  data () {
    return {
      classifyDateRange: '',
      participantsDateRange: '',
      hasClassifyData: false,
      hasParticipantsData: false,
      classifyPieOptions: {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: '#666',
            fontSize: 14
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          itemWidth: 12,
          itemHeight: 12,
          textStyle: {
            color: '#666',
            fontSize: 14
          },
          formatter: function (name) {
            return name.length > 12 ? name.slice(0, 12) + '...' : name
          }
        },
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#8cc5ff', '#95d475', '#ffd666', '#ff9f7f', '#c6cbd4'],
        series: [
          {
            name: '活动分类',
            type: 'pie',
            radius: ['45%', '70%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}个',
              color: '#666',
              fontSize: 13,
              lineHeight: 18,
              padding: [0, 0, 0, 10]
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 15,
              smooth: true,
              lineStyle: {
                color: '#eee',
                width: 1.5
              }
            },
            emphasis: {
              scale: true,
              scaleSize: 10,
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.2)'
              }
            },
            data: []
          }
        ]
      },
      participantsBarOptions: {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}人',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: '#666',
            fontSize: 14
          }
        },
        grid: {
          top: '3%',
          left: '15%',
          right: '8%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '参与人数',
          nameTextStyle: {
            color: '#666',
            fontSize: 14,
            padding: [0, 0, 5, 0]
          },
          axisLabel: {
            formatter: '{value}人',
            color: '#666',
            fontSize: 12,
            margin: 12
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eee',
              width: 1
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5',
              type: 'dashed',
              width: 1
            }
          }
        },
        yAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            color: '#666',
            fontSize: 13,
            margin: 16,
            width: 200,
            overflow: 'break',
            lineHeight: 20,
            formatter: function (value) {
              const maxLength = 20
              if (value.length > maxLength) {
                return value.substring(0, maxLength) + '...'
              }
              return value
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eee',
              width: 1
            }
          }
        },
        series: [
          {
            name: '参与人数',
            type: 'bar',
            data: [],
            barWidth: '40%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                  {
                    offset: 0,
                    color: '#409EFF'
                  },
                  {
                    offset: 1,
                    color: '#69b1ff'
                  }
                ]
              },
              borderRadius: [0, 4, 4, 0],
              shadowColor: 'rgba(0, 0, 0, 0.1)',
              shadowBlur: 10
            },
            label: {
              show: true,
              position: 'right',
              distance: 10,
              formatter: '{c}人',
              textStyle: {
                color: '#666',
                fontSize: 13,
                fontWeight: 500
              }
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 0,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#66b1ff'
                    },
                    {
                      offset: 1,
                      color: '#8cc5ff'
                    }
                  ]
                },
                shadowColor: 'rgba(0, 0, 0, 0.2)',
                shadowBlur: 15
              }
            }
          }
        ]
      },
      statusData: [
        {
          label: '未开始',
          value: 0,
          icon: 'el-icon-time',
          color: 'rgba(64, 158, 255, 0.1)'
        },
        {
          label: '进行中',
          value: 0,
          icon: 'el-icon-video-play',
          color: 'rgba(103, 194, 58, 0.1)'
        },
        {
          label: '已结束',
          value: 0,
          icon: 'el-icon-circle-close',
          color: 'rgba(245, 108, 108, 0.1)'
        },
        {
          label: '总活动数',
          value: 0,
          icon: 'el-icon-data-analysis',
          color: 'rgba(144, 147, 153, 0.1)'
        }
      ]
    }
  },
  methods: {
    // 更新图表主题
    updateChartTheme () {
      // 更新饼图主题
      this.classifyPieOptions = {
        ...this.classifyPieOptions,
        backgroundColor: 'transparent',
        tooltip: {
          ...this.classifyPieOptions.tooltip,
          backgroundColor: this.chartTheme.tooltipBackground,
          borderColor: this.chartTheme.tooltipBorderColor,
          textStyle: {
            color: this.chartTheme.textColor
          }
        },
        legend: {
          ...this.classifyPieOptions.legend,
          textStyle: {
            color: this.chartTheme.textColor
          }
        },
        series: [
          {
            ...this.classifyPieOptions.series[0],
            itemStyle: {
              ...this.classifyPieOptions.series[0].itemStyle,
              borderColor: this.isDarkTheme ? '#1e1e1e' : '#fff'
            },
            label: {
              ...this.classifyPieOptions.series[0].label,
              color: this.chartTheme.textColor
            },
            labelLine: {
              ...this.classifyPieOptions.series[0].labelLine,
              lineStyle: {
                color: this.chartTheme.axisLineColor
              }
            }
          }
        ]
      }

      // 更新柱状图主题
      this.participantsBarOptions = {
        ...this.participantsBarOptions,
        backgroundColor: 'transparent',
        tooltip: {
          ...this.participantsBarOptions.tooltip,
          backgroundColor: this.chartTheme.tooltipBackground,
          borderColor: this.chartTheme.tooltipBorderColor,
          textStyle: {
            color: this.chartTheme.textColor
          }
        },
        xAxis: {
          ...this.participantsBarOptions.xAxis,
          nameTextStyle: {
            ...this.participantsBarOptions.xAxis.nameTextStyle,
            color: this.chartTheme.textColor
          },
          axisLabel: {
            ...this.participantsBarOptions.xAxis.axisLabel,
            color: this.chartTheme.textColor
          },
          axisLine: {
            ...this.participantsBarOptions.xAxis.axisLine,
            lineStyle: {
              color: this.chartTheme.axisLineColor
            }
          },
          splitLine: {
            ...this.participantsBarOptions.xAxis.splitLine,
            lineStyle: {
              color: this.chartTheme.splitLineColor,
              type: 'dashed'
            }
          }
        },
        yAxis: {
          ...this.participantsBarOptions.yAxis,
          axisLabel: {
            ...this.participantsBarOptions.yAxis.axisLabel,
            color: this.chartTheme.textColor
          },
          axisLine: {
            ...this.participantsBarOptions.yAxis.axisLine,
            lineStyle: {
              color: this.chartTheme.axisLineColor
            }
          }
        },
        series: [
          {
            ...this.participantsBarOptions.series[0],
            label: {
              ...this.participantsBarOptions.series[0].label,
              textStyle: {
                color: this.chartTheme.textColor,
                fontSize: 12
              }
            }
          }
        ]
      }

      // 更新状态饼图主题
      this.statusPieOptions = {
        ...this.statusPieOptions,
        backgroundColor: 'transparent',
        tooltip: {
          ...this.statusPieOptions.tooltip,
          backgroundColor: this.chartTheme.tooltipBackground,
          borderColor: this.chartTheme.tooltipBorderColor,
          textStyle: {
            color: this.chartTheme.textColor
          }
        },
        legend: {
          ...this.statusPieOptions.legend,
          textStyle: {
            color: this.chartTheme.textColor
          }
        },
        series: [
          {
            ...this.statusPieOptions.series[0],
            itemStyle: {
              ...this.statusPieOptions.series[0].itemStyle,
              borderColor: this.isDarkTheme ? '#1e1e1e' : '#fff'
            },
            label: {
              ...this.statusPieOptions.series[0].label,
              color: this.chartTheme.textColor
            },
            labelLine: {
              ...this.statusPieOptions.series[0].labelLine,
              lineStyle: {
                color: this.chartTheme.axisLineColor
              }
            }
          }
        ]
      }
    },
    // 获取分类统计数据
    async getClassifyData () {
      try {
        const begin = this.classifyDateRange ? this.classifyDateRange[0] : ''
        const end = this.classifyDateRange ? this.classifyDateRange[1] : ''
        console.log('请求分类统计参数：', { begin, end })
        const response = await getClassifyStatistics(begin, end)
        console.log('分类统计响应：', response)

        if (response && response.code === 1 && response.data) {
          if (!response.data.nameList || !response.data.numberList) {
            this.hasClassifyData = false
            return
          }

          const names = response.data.nameList.split(',').filter(name => name.trim() !== '')
          const numbers = response.data.numberList.split(',')
            .filter(num => num.trim() !== '')
            .map(num => parseInt(num, 10))

          const minLength = Math.min(names.length, numbers.length)
          if (minLength === 0) {
            this.hasClassifyData = false
            return
          }

          const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#8cc5ff', '#95d475', '#ffd666', '#ff9f7f', '#c6cbd4']
          const chartData = names.slice(0, minLength).map((name, index) => ({
            name: name || '未命名分类',
            value: numbers[index] || 0,
            itemStyle: {
              color: colors[index % colors.length]
            }
          }))

          this.classifyPieOptions.series[0].data = chartData
          this.hasClassifyData = true
        } else {
          this.hasClassifyData = false
        }
      } catch (error) {
        console.error('获取分类统计数据失败：', error)
        this.$message.error('获取分类统计数据失败')
        this.hasClassifyData = false
      }
    },

    // 获取活动参与人数 Top10
    async getTop10Data () {
      try {
        const begin = this.participantsDateRange ? this.participantsDateRange[0] : ''
        const end = this.participantsDateRange ? this.participantsDateRange[1] : ''
        console.log('Top10请求参数：', { begin, end })

        const response = await getActivityTop10(begin, end)
        console.log('Top10响应：', response)

        if (response && response.code === 1 && response.data) {
          // 检查返回的数据是否为空
          if (!response.data.activityTitleList || !response.data.activityPropleNumberList) {
            this.hasParticipantsData = false
            return
          }

          // 将字符串转换为数组，并过滤掉空值
          const titles = response.data.activityTitleList.split(',').filter(title => title.trim() !== '')
          const numbers = response.data.activityPropleNumberList.split(',')
            .filter(num => num.trim() !== '')
            .map(num => parseInt(num, 10))

          // 确保两个数组长度一致且有数据
          const minLength = Math.min(titles.length, numbers.length)
          if (minLength === 0) {
            this.hasParticipantsData = false
            return
          }

          const validTitles = titles.slice(0, minLength)
          const validNumbers = numbers.slice(0, minLength)

          // 创建数据对象数组并排序
          const combinedData = validTitles.map((title, index) => ({
            title: title || '未命名活动',
            number: validNumbers[index] || 0
          })).sort((a, b) => b.number - a.number)

          // 更新图表据
          this.participantsBarOptions.yAxis.data = combinedData.map(item => item.title)
          this.participantsBarOptions.series[0].data = combinedData.map(item => item.number)
          this.hasParticipantsData = true
        } else {
          this.hasParticipantsData = false
        }
      } catch (error) {
        console.error('获取活动参与人数统计失败：', error)
        this.$message.error('获取活动参与人数统计失败')
        this.hasParticipantsData = false
      }
    },

    // 获取活动状态统计
    async getStatusData () {
      try {
        console.log('请求活动状态统计')
        const response = await getActivityStatistics()
        console.log('状态统计响应：', response)
        if (response && response.code === 1) {
          this.statusData[0].value = response.data.haveNotStarted || 0
          this.statusData[1].value = response.data.underway || 0
          this.statusData[2].value = response.data.canceled || 0
          this.statusData[3].value = response.data.all || 0
        }
      } catch (error) {
        console.error('获取活动状态统计失败：', error)
        this.$message.error('获取活动状态统计失败')
      }
    },

    // 活动分类日期变化处理
    handleClassifyDateChange () {
      this.getClassifyData()
    },

    // 活动参与人数日期变化处理
    handleParticipantsDateChange () {
      this.getTop10Data()
    },

    // 初始化所有图表数据
    initChartData () {
      this.getClassifyData()
      this.getTop10Data()
      this.getStatusData()
    }
  },
  created () {
    this.initChartData()
  }
}
</script>

<style scoped>
.home-dashboard {
  padding: 20px;
  background-color: var(--background-color);
  min-height: calc(100vh - 120px);
}

.chart-card {
  margin-bottom: 20px;
  box-shadow: var(--box-shadow);
  background-color: var(--card-background);
  border-radius: 12px;
  border: 1px solid var(--border-color);
  height: 500px;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.chart-card.large {
  min-height: 600px;
  height: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  display: flex;
  align-items: center;
}

.chart-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background: var(--primary-color);
  margin-right: 8px;
  border-radius: 2px;
}

.chart-container {
  flex: 1;
  position: relative;
  height: 400px;
}

.chart-container.large {
  min-height: 500px;
  height: auto;
}

.chart-container :deep(.echarts) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 100% !important;
}

.status-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  padding: 24px;
  min-height: 0;
}

.status-item {
  position: relative;
  padding: 24px;
  border-radius: 12px;
  background-color: var(--card-background);
  border: 1px solid var(--border-color);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: all 0.3s ease;
}

.status-item:hover {
  transform: translateY(-3px);
  box-shadow: var(--hover-shadow);
}

.status-value {
  font-size: 32px;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 12px;
  position: relative;
  z-index: 1;
}

.status-label {
  font-size: 15px;
  color: var(--text-color-secondary);
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
}

.status-icon {
  position: absolute;
  right: 24px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 54px;
  opacity: 0.15;
  color: var(--text-color);
  transition: all 0.3s ease;
}

.status-item:hover .status-icon {
  opacity: 0.25;
  transform: translateY(-50%) scale(1.1);
}

.status-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.5;
  transition: all 0.3s ease;
}

.status-item:hover .status-bg {
  opacity: 0.7;
}

.empty-state {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-color-secondary);
  padding: 40px;
}

.empty-state i {
  font-size: 54px;
  margin-bottom: 16px;
  opacity: 0.8;
  transition: all 0.3s ease;
}

.empty-state:hover i {
  transform: scale(1.1);
  opacity: 1;
}

.empty-state p {
  margin: 0;
  font-size: 15px;
  line-height: 1.6;
}

.date-picker {
  width: 260px;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--scrollbar-track);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--scrollbar-thumb);
  border-radius: 4px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--scrollbar-thumb-hover);
}

/* 返回顶部按钮样式 */
.back-to-top {
  height: 100%;
  width: 100%;
  background-color: var(--primary-color);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-to-top:hover {
  background-color: var(--primary-hover);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
</style>
